<script lang="ts" setup>
import { ref, onUnmounted } from 'vue'
import { loginByPassword, getCode, codeLogin } from '@/api/user'
import { useUserStore } from '@/stores'
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
import { showToast } from 'vant'
import type { FormInstance } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { useCode } from '@/hook'
const router = useRouter()
const route = useRoute()
const store = useUserStore()
const agree = ref(true)
// 定义模型
const mobile = ref('13230000001')
const password = ref('abc12345')
const code = ref('')
// 是否展示密码框
const isShowPassword = ref(false)
// 是否是密码登录
const isPassword = ref(true)
// const formRef = ref<FormInstance>()
const { form, timer, time, send } = useCode(mobile)
const rightClick = () => {
  console.log('---登录页面感知到了，点击右上方的注册---')
}
const login = async () => {
  try {
    const res = isPassword.value
      ? await loginByPassword({
          mobile: mobile.value,
          password: password.value
        })
      : await codeLogin({
          mobile: mobile.value,
          code: code.value
        })

    // 保存到仓库中
    store.setUser(res.data)

    // 跳转到
    if (route.query.redirect) {
      // 跳转到重定向地址
      router.replace(route.query.redirect as string)
    } else {
      // 默认跳转到 user
      router.push('/user')
    }
  } catch (error) {
    console.log(error)
  }
}
// 发送验证码
// const time = ref(0)
// let timer = -1 // 因为定时器的值是大于0的，-1代表暂时没有
// const send = async () => {
//   // 校验手机号
//   try {
//     if (time.value > 0) return
//     await formRef.value?.validate(['mobile'])

//     // 发送请求，获取验证码
//     const res = await getCode(mobile.value)

//     showToast(res.data.code)
//     // 倒计时
//     time.value = 60
//     clearInterval(timer)
//     timer = window.setInterval(() => {
//       time.value--
//       if (time.value <= 0) {
//         clearInterval(timer)
//       }
//     }, 1000)
//   } catch (error) {
//     console.log('---error---', error)
//   }
// }
onUnmounted(() => {
  clearInterval(timer)
})
const qqUrl =
  'https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fconsult-patients.itheima.net%2Flogin%2Fcallback'
</script>

<template>
  <div class="login-page">
    <cp-nav-bar right-text="注册" @right-click="rightClick" />
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPassword ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPassword = !isPassword">
        <span>{{ isPassword ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form class="van-form" @submit="login" ref="form">
      <van-field placeholder="请输入手机号" v-model="mobile" :rules="mobileRules" name="mobile" />
      <van-field
        placeholder="请输入密码"
        :type="isShowPassword ? 'text' : 'password'"
        v-model="password"
        :rules="passwordRules"
        v-if="isPassword"
        name="password"
      >
        <template #button>
          <cp-icon
            @click="isShowPassword = !isShowPassword"
            :name="isShowPassword ? 'login-eye-on' : 'login-eye-off'"
          />
        </template>
      </van-field>
      <van-field v-else placeholder="短信验证码" :rules="codeRules" v-model="code" name="code">
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">{{
            time > 0 ? `${time}秒后重试` : '发送验证码'
          }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <a :href="qqUrl">
          <img src="@/assets/qq.svg" alt="" />
        </a>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    // padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
